package com.chinatelecom.otms.circuitcheck.service;

import com.chinatelecom.otms.circuitcheck.dao.CheckCircuitDao;
import com.chinatelecom.otms.circuitcheck.dao.SncDao;
import com.chinatelecom.otms.circuitcheck.dao.SncRouteDao;
import com.chinatelecom.otms.circuitcheck.dao.TopoLinkDao;
import com.chinatelecom.otms.circuitcheck.entity.*;
import com.chinatelecom.otms.circuitcheck.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CheckCircuitService {
    @Autowired
    private CheckCircuitDao checkCircuitDao;
    @Autowired
    private SncRouteDao sncRouteDao;
    @Autowired
    private SncDao sncDao;
    @Autowired
    private TopoLinkDao topoLinkDao;

    private static List<Snc> sncsList = new ArrayList<>();

    public void truncateTableAndInsertChechCircuit(List<CheckCircuit> checkCircuitList, boolean isTruncateTable) throws InterruptedException {
        if(isTruncateTable){
            checkCircuitDao.truncateTable();
            System.out.println(Common.TABLE_NAME + " 表清空成功");
        }
        Integer count = checkCircuitDao.insertCheckCircuitList(checkCircuitList);
        System.out.println(Common.TABLE_NAME + " 表插入数据个数：" + count);
    }

    public CheckCircuit updateSncByInterface(CheckCircuit checkCircuit) throws IOException {
        String sncTestResult = HttpUtil.postInterfaceBySncAndEms(WebInterface.GET_SNC_URL, WebBody.GET_SNC_BODY, checkCircuit.getSnc_id(), checkCircuit.getEms_id());
        String desc = HttpUtil.getDescByResponseStr(sncTestResult);
        checkCircuit.setRoute_desc("getSNC:" + desc);
        System.out.println("获取getSNC，SNC_ID: " + checkCircuit.getSnc_id() + ", 结果：" + desc);
        return checkCircuit;
    }

    public CheckCircuit updateRouteDescBySncRef(CheckCircuit checkCircuit) throws IOException {
        String routeTestResult = HttpUtil.postInterfaceBySncAndEms(WebInterface.GET_ROUTE_URL, WebBody.GET_ROUTE_BODY, checkCircuit.getSnc_id(), checkCircuit.getEms_id());
        String desc = HttpUtil.getDescByResponseStr(routeTestResult);
        checkCircuit.setRoute_desc(desc);
        System.out.println("获取getRoute，SNC_ID: " + checkCircuit.getSnc_id() + ", 结果：" + desc);
        return checkCircuit;
    }

    public List<CheckCircuit> getEmsIdByCheckCircuitList(List<CheckCircuit> checkCircuitList) {
        for(CheckCircuit checkCircuit : checkCircuitList){
            checkCircuit.setEms_id(System.getenv("ems_id"));
        }
        return checkCircuitList;
    }

    private String getEmsIdByVendorObjName(String vendor_obj_name){
        return vendor_obj_name.split(";")[0].split("=")[1];
    }

    public List<CheckCircuit> checkAZPTPContrastResultAndUpdate(List<CheckCircuit> checkCircuitLists) throws NoSuchFieldException, IllegalAccessException {
        Map<String, List<SncRoute>> sncRoute_Map = sncRouteDao.getSncRouteListsBySncIdAndWayType(checkCircuitLists);
        Map<String, String> checkAZConstractMap = checkAZPTPContrastResultAndUpdateByList(sncRoute_Map, sncsList);
        for(CheckCircuit checkCircuit : checkCircuitLists){
            checkCircuit.setA_z_ptp_result(checkAZConstractMap.get(checkCircuit.getSnc_id()));
        }
        return checkCircuitLists;
    }

    private Map<String, String> checkAZPTPContrastResultAndUpdateByList(Map<String, List<SncRoute>> map, List<Snc> sncsList) throws NoSuchFieldException, IllegalAccessException {
        Map<String, String> azConstrastResultsMap = new HashMap<>();
        for(Snc snc : sncsList){
            List<SncRoute> sncRouteslist = map.get(snc.getSnc_id());
            if(sncRouteslist != null && sncRouteslist.size() != 0){
                Map<String, List<SncRoute>> sncRoutewayTypeMap = new Common<SncRoute>().classifyListByStringParams(sncRouteslist, "way_type");
                Object[] objects = sncRoutewayTypeMap.keySet().toArray();
                for(Object o : objects){
                    String way_type = (String) o;
                    AZConstrastResult azConstrastResult = checkAZPTPContrastResultDetail(sncRoutewayTypeMap.get(way_type), way_type, snc);
                    if(azConstrastResult != null){
                        azConstrastResultsMap.put(azConstrastResult.getSnc_id(), azConstrastResult.getConstrastResult());
                    }
                }
            }else{
                azConstrastResultsMap.put(snc.getSnc_id(), "SNC_ROUTE 无SNC数据，对比AZ端失败");
            }

        }
        return azConstrastResultsMap;
    }

    private AZConstrastResult checkAZPTPContrastResultDetail(List<SncRoute> sncRouteslist, String next, Snc snc) {
        sncRouteslist.sort((x, y) -> Integer.compare(Integer.valueOf(x.getOrder_no()), Integer.valueOf(y.getOrder_no())));
        if(next.equals(WayType.WAY_TYPE_FORWARD)){
            if(!sncRouteslist.get(0).getA_ptp_id().equals(snc.getA_ptp_id()) || !sncRouteslist.get(sncRouteslist.size() - 1).getZ_ptp_id().equals(snc.getZ_ptp_id())){
                return new AZConstrastResult(snc.getSnc_id(), "SNC AZ端与 SNC_ROUTE AZ端不匹配，正向");
            }else{
                return checkIfAZRightInList(sncRouteslist, next, snc);
            }
        }else if(next.equals(WayType.WAY_TYPE_REVERSE)){
            if(!sncRouteslist.get(0).getA_ptp_id().equals(snc.getZ_ptp_id()) || !sncRouteslist.get(sncRouteslist.size() - 1).getZ_ptp_id().equals(snc.getA_ptp_id())){
                return new AZConstrastResult(snc.getSnc_id(), "SNC AZ端与 SNC_ROUTE AZ端不匹配，反向");
            }else{
                return checkIfAZRightInList(sncRouteslist, next, snc);
            }
        }
        return null;
    }

    private AZConstrastResult checkIfAZRightInList(List<SncRoute> list, String way_type, Snc snc) {
        for(int i = 0; i < list.size() - 2; i ++){
            if(!list.get(i).getZ_ptp_id().equals(list.get(i + 1).getA_ptp_id())){
                return new AZConstrastResult(snc.getSnc_id(), "SNC_ROUTE 串接失败，WAY_TYPE=" + way_type + ", ORDER_NO: " + list.get(i).getOrder_no());
            }
        }
        return new AZConstrastResult(snc.getSnc_id(), "SUCCESS");
    }

    public List<CheckCircuit> checkCarrierAndSncRoute(List<CheckCircuit> checkCircuitsList) {
        for(CheckCircuit checkCircuit : checkCircuitsList){
            List<CheckCarrierAndSncRouteResult> checkCarrierAndSncRouteList = checkCircuitDao.checkCarrierAndSncRoute(checkCircuit.getSnc_id());
            if(checkCarrierAndSncRouteList == null || checkCarrierAndSncRouteList.size() == 0){
                checkCircuit.setSnc_route_in_carrier_result("SUCCESS");
            }else{
                checkCircuit.setSnc_route_in_carrier_result("SNC_ROUTE 在CARRIER内有不存在的SNC size:" + checkCarrierAndSncRouteList.size());
            }
        }
        return checkCircuitsList;
    }

    public List<CheckCircuit> checkFDFRinCarrier(List<CheckCircuit> checkCircuitsList) {
        for(CheckCircuit checkCircuit : checkCircuitsList){
            List<FDFRCarrierResult> fdfrCarrierResultsList = checkCircuitDao.checkFDFRinCarrier(checkCircuit.getSnc_id());
            FDFRCarrierResult fDFRCarrierResult = new FDFRCarrierResult();
            if(fdfrCarrierResultsList != null || fdfrCarrierResultsList.size() != 0){
                fDFRCarrierResult = fdfrCarrierResultsList.get(0);
            }
            String result = "";
            if(fDFRCarrierResult.getFdfr_exist() == null || fDFRCarrierResult.getFdfr_exist().equals("")){
                result = result + "FDFR不存在  ";
            }else{
                result = result + "FDFR: " + fDFRCarrierResult.getFdfr_exist();
            }
            if(fDFRCarrierResult.getFdfr_h_exist() == null || fDFRCarrierResult.getFdfr_h_exist().equals("")){
                result = result + " FDFR_H不存在  ";
            }else{
                result = result + " FDFR_H: " + fDFRCarrierResult.getFdfr_h_exist();
            }
            if(fDFRCarrierResult.getCarrier_exist() == null || fDFRCarrierResult.getCarrier_exist().equals("")){
                result = result + " CARRIER不存在  ";
            }else{
                result = result + " CARRIER: " + fDFRCarrierResult.getCarrier_exist();
            }
            if(fDFRCarrierResult.getCarrier_h_exist() == null || fDFRCarrierResult.getCarrier_h_exist().equals("")){
                result = result + " CARRIER_H不存在  ";
            }else{
                result = result + " CARRIER_H: " + fDFRCarrierResult.getCarrier_h_exist();
            }
            if(fDFRCarrierResult.getTrace_id() == null || fDFRCarrierResult.getTrace_id().equals("")){
                result = result + " TRACE_ID不存在  ";
            }else{
                result = result + " TRACE_ID: " + fDFRCarrierResult.getTrace_id();
            }
            checkCircuit.setFdfr_carrier_result(result);
        }
        return checkCircuitsList;
    }

    public List<CheckCircuit> checkMFDFRinPort(List<CheckCircuit> checkCircuitsList, boolean isCheckPTP) {
        for (CheckCircuit checkCircuit : checkCircuitsList){
            List<MFDFRPortResult> mfdfrPortResultsList = checkCircuitDao.checkMFDFRPort(checkCircuit.getSnc_id(), isCheckPTP);
            if(mfdfrPortResultsList != null && mfdfrPortResultsList.size() == 2){
                String result = mfdfrPortResultsList.get(0).getEms_id() + "网管, 端口:"
                        + mfdfrPortResultsList.get(0).getPort_id() + ", TP_TYPE:" + mfdfrPortResultsList.get(0).getTp_type();
                result = result + ", 端口:" + mfdfrPortResultsList.get(1).getPort_id() + ", TP_TYPE: " + mfdfrPortResultsList.get(1).getTp_type();
                checkCircuit.setMfdfr_port_result(result);
            }else if(mfdfrPortResultsList != null && mfdfrPortResultsList.size() == 1){
                String result = mfdfrPortResultsList.get(0).getEms_id() + "网管, 端口:"
                        + mfdfrPortResultsList.get(0).getPort_id() + ", TP_TYPE:" + mfdfrPortResultsList.get(0).getTp_type();
                result = result + ", 另一端口在PORT表内不存在";
                checkCircuit.setMfdfr_port_result(result);
            }else{
                checkCircuit.setMfdfr_port_result("MFDFR PORT在PORT表内不存在，或MFDFR在MFDFR表内不存在");
            }

        }
        return checkCircuitsList;
    }

    public List<CheckCircuit> checkFDFRRouteInSncAndMFDFR(List<CheckCircuit> checkCircuitsList) {
        for(CheckCircuit checkCircuit : checkCircuitsList){
            List<CheckFDFRRouteInSncAndMFDFRResult> list
                    = checkCircuitDao.checkFDFRRouteInSncAndMFDFR(checkCircuit.getSnc_id());
            CheckFDFRRouteInSncAndMFDFRResult tempResult = list.get(0);
            if(tempResult != null){
                switch (tempResult.getRoute_type()){
                    case "4":
                        if(tempResult.getMfdfr() == null){
                            checkCircuit.setFdfr_route_relevance("ROUTE_TYPE:4 " + "MFDFR:null");
                        }else{
                            checkCircuit.setFdfr_route_relevance("ROUTE_TYPE:4 " + "MFDFR:" + tempResult.getMfdfr());
                        }
                        break;
                    case "3":
                        if(tempResult.getSnc() == null){
                            checkCircuit.setFdfr_route_relevance("ROUTE_TYPE:3 " + "SNC:null");
                        }else{
                            checkCircuit.setFdfr_route_relevance("ROUTE_TYPE:3 " + "SNC:" + tempResult.getSnc());
                        }
                        break;
                }
            }else{
                checkCircuit.setFdfr_route_relevance("T_FDFR_ROUTE无数据");
            }
        }
        return checkCircuitsList;
    }

    public List<String> checkL2LinkRoute(List<CheckCircuit> checkCircuitsList) {
        List<String> resultList = new ArrayList<>();
        for(CheckCircuit checkCircuit : checkCircuitsList){
            List<CheckL2LinkRouteResult> checkL2LinkRouteList = checkCircuitDao.checkL2LinkRoute(checkCircuit.getSnc_id());
            for(CheckL2LinkRouteResult checkL2LinkRoute : checkL2LinkRouteList){
                if(checkL2LinkRoute.getSnc_type() == 1){
                    List<L2LinkTempResult> list1 =  checkCircuitDao.getAZPortByobjId(checkCircuit.getSnc_id());
                    List<L2LinkTempResult> list2 =  checkCircuitDao.getAZPortBySncId(checkL2LinkRoute.getSnc_id());
                    L2LinkTempResult l2LinkTempResult_1 = list1.get(0);
                    L2LinkTempResult l2LinkTempResult_2 = list2.get(0);
                    if(l2LinkTempResult_1.getA_port_id().equals(l2LinkTempResult_2.getA_port_id())
                            && l2LinkTempResult_1.getZ_port_id().equals(l2LinkTempResult_2.getZ_port_id())){
                        continue;
                    }else if(l2LinkTempResult_1.getA_port_id().equals(l2LinkTempResult_2.getZ_port_id())
                            && l2LinkTempResult_1.getZ_port_id().equals(l2LinkTempResult_2.getA_port_id())){
                        continue;
                    }else{
                        resultList.add(checkCircuit.getSnc_id() + " " + checkL2LinkRoute.getSnc_id());
                    }
                }
            }
        }

        return resultList;
    }

    public List<CheckCircuit> checkPortStateVlan(List<CheckCircuit> checkCircuitsList) {
        for(CheckCircuit checkCircuit : checkCircuitsList){
            List<CheckPortStateVlanResult> list = checkCircuitDao.checkPortStateVlan(checkCircuit.getSnc_id());
            if(list == null || list.get(0) == null){
                checkCircuit.setPort_state_vlan("无数据");
                continue;
            }
            CheckPortStateVlanResult checkPortStateVlanResult = list.get(0);
            String result = "";
            if(checkPortStateVlanResult != null){
                if(checkPortStateVlanResult.getZ_port_id() != null){
                    result = result + "Z_PORT_ID:" + checkPortStateVlanResult.getZ_port_id() + " ";
                }else{
                    result = result + "Z_PORT_ID为空 ";
                }
                if(checkPortStateVlanResult.getSvlan() != null){
                    result = result + "SVLAN:" + checkPortStateVlanResult.getSvlan() + " ";
                }else{
                    result = result + "SVLAN为空 ";
                }
                if(checkPortStateVlanResult.getVlan_mode() != null){
                    result = result + "VLAN_MODE:" + checkPortStateVlanResult.getVlan_mode() + " ";
                }else{
                    result = result + "VLAN_MODE为空 ";
                }
            }else{
                checkCircuit.setPort_state_vlan("无数据");
            }
            checkCircuit.setPort_state_vlan(result);
        }
        return checkCircuitsList;
    }

    public List<String> checkBindingRel(List<CheckCircuit> checkCircuitsList) {
        List<String> resultList = new ArrayList<>();
        for(CheckCircuit checkCircuit : checkCircuitsList){
            List<CheckBindingRelResult> list = checkCircuitDao.checkBindingRel(checkCircuit.getSnc_id());
            CheckBindingRelResult checkBindingRelResult = list.get(0);
            String result = checkCircuit.getSnc_id() + " ";
            if(checkBindingRelResult.getMaster_port_id() != null){
                result = result + "Master PortId: " + checkBindingRelResult.getMaster_port_id();
            }else{
                result = result + "Master PortId为空 ";
            }
            if(checkBindingRelResult.getSlave_port_id() != null){
                result = result + " Slave PortId: " + checkBindingRelResult.getSlave_port_id();
            }else{
                result = result + " Slave PortId为空 ";
            }
            resultList.add(result);
        }
        return resultList;
    }

    public List<String> checkFTPBindingRel(List<CheckCircuit> checkCircuitsList) {
        List<String> resultList = new ArrayList<>();
        for(CheckCircuit checkCircuit : checkCircuitsList){
            List<CheckFTPBindingRelResult> list = checkCircuitDao.checkFTPBindingRel(checkCircuit.getSnc_id());
            CheckFTPBindingRelResult checkFTPBindingRelResult = list.get(0);
            if(checkFTPBindingRelResult != null){
                String tempstr = checkCircuit.getSnc_id() + " ";
                if(checkFTPBindingRelResult.getMaster_object_id() != null){
                    tempstr = tempstr + " master_object_id: " + checkFTPBindingRelResult.getMaster_object_id();
                }else{
                    tempstr = tempstr + " master_object_id为空 ";
                }
                if(checkFTPBindingRelResult.getLayerrate_list() != null){
                    tempstr = tempstr + " layerrate_list: " + checkFTPBindingRelResult.getLayerrate_list();
                }else{
                    tempstr = tempstr + " layerrate_list为空 ";
                }
                if(checkFTPBindingRelResult.getFtp_id() != null){
                    tempstr = tempstr + " ftp_id: " + checkFTPBindingRelResult.getFtp_id();
                }else{
                    tempstr = tempstr + " ftp_id为空 ";
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
                if(checkFTPBindingRelResult.getReceive_time() != null){
                    tempstr = tempstr + " receive_time: " + sdf.format(checkFTPBindingRelResult.getReceive_time());
                }
                resultList.add(tempstr);
            }else{
                resultList.add(checkCircuit.getSnc_id() + " 无数据");
            }
        }
        return resultList;
    }

    public CheckCircuit getAllEquipments(CheckCircuit checkCircuit) throws IOException {
        String topoResult = HttpUtil.postGetAllEquipments(WebInterface.GET_EQ_URL, WebBody.GET_EQ_BODY, "FA358C2717FC47EDAB07BB997AECADAB", checkCircuit.getSnc_id());
        String descByResponseStr = HttpUtil.getDescByResponseStr(topoResult);
        checkCircuit.setGetAllEquipmentsResult(descByResponseStr);
        return checkCircuit;
    }


    public CheckCircuit getAllPhysicalTerminationPointsWithoutFtps(CheckCircuit checkCircuit) throws IOException {
        String topoResult = HttpUtil.postGetAllPhysicalTerminationPointsWithoutFtps(WebInterface.GET_PTP_URL, WebBody.GET_PTP_BODY, checkCircuit.getEms_id(), checkCircuit.getSnc_id());
        String descByResponseStr = HttpUtil.getDescByResponseStr(topoResult);
        checkCircuit.setPtpResult(descByResponseStr);
        return checkCircuit;
    }

    public CheckCircuit getFDFR(CheckCircuit checkCircuit) throws IOException {
        String topoResult = HttpUtil.postGetFDFR(WebInterface.GET_FDFR_URL, WebBody.GET_FDFR_BODY, "FA358C2717FC47EDAB07BB997AECADAB", checkCircuit.getSnc_id());
        String descByResponseStr = HttpUtil.getDescByResponseStr(topoResult);
        checkCircuit.setGetAllEquipmentsResult("getFDFR:" + descByResponseStr);
        return checkCircuit;
    }

    public CheckCircuit getFDFRRoute(CheckCircuit checkCircuit) throws IOException {
        String topoResult = HttpUtil.postGetFDFRRoute(WebInterface.GET_FDFR_ROUTE_URL, WebBody.GET_FDFR_ROUTE_BODY, "FA358C2717FC47EDAB07BB997AECADAB", checkCircuit.getSnc_id());
        String descByResponseStr = HttpUtil.getDescByResponseStr(topoResult);
        checkCircuit.setGetAllEquipmentsResult(descByResponseStr);
        return checkCircuit;
    }
}